package com.central.oss.template

import cn.hutool.core.util.IdUtil
import com.aliyun.oss.OSSClient
import com.aliyun.oss.common.auth.DefaultCredentialProvider
import com.central.oss.model.ObjectInfo
import com.central.oss.properties.FileServerProperties
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.web.multipart.MultipartFile
import java.io.InputStream
import javax.annotation.Resource

/**
 * @author  fly
 * @date  2021/5/28 14:19
 * @version 1.0
 */
@ConditionalOnClass(OSSClient::class)
@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = ["type"], havingValue = FileServerProperties.TYPE_ALI)
open class AliTemplate {

    @Resource
    private lateinit var fileServerProperties: FileServerProperties


    fun uploadFile(file: MultipartFile): ObjectInfo = ObjectInfo().apply {
        objectUrl = aliInputStreamUpload(file.inputStream, renamePic(file.originalFilename!!))
    }


    private fun aliInputStreamUpload(inputStream: InputStream, key: String) : String {

        val ossClient = OSSClient(
            fileServerProperties.ali.http + fileServerProperties.ali.endpoint, DefaultCredentialProvider(fileServerProperties.ali.accessKey, fileServerProperties.ali.secretKey),
            null)
        ossClient.putObject(fileServerProperties.ali.bucket, key, inputStream)
        ossClient.shutdown()
        return fileServerProperties.ali.http.plus(fileServerProperties.ali.bucket).plus(".")
            .plus(fileServerProperties.ali.endpoint).plus("/").plus(key)

    }

    /**
     * 以UUID重命名
     * @param fileName
     * @return
     */
    open fun renamePic(fileName: String): String {

        val extName = fileName.substring(fileName.lastIndexOf("."))
        return IdUtil.simpleUUID() + extName
    }
}